package com.teamsun.mqtt.runnable;

import org.apache.log4j.Logger;

import com.teamsun.mqtt.entity.SendMsg;
import com.teamsun.mqtt.entity.vo.SendableMsg;
import com.teamsun.mqtt.service.MessagePushService;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;


/**
 * 重发机制运行的代码
 * @author tzj
 *
 */
public class ResendRunnable implements  Runnable{
	
	MessagePushService messagePushService;
	Channel channel;
	SendableMsg sendableMsg;
	
	Logger logger=Logger.getLogger(getClass());
	
	int  maxresendtime=3;

	public ResendRunnable() {
	
	}

	public ResendRunnable(MessagePushService messagePushService, Channel channel, SendableMsg sendableMsg) {
		super();
		this.messagePushService = messagePushService;
		this.channel = channel;
		this.sendableMsg = sendableMsg;
	}




	@Override
	public void run() {
		
		AttributeKey<Boolean>  attributeKey=AttributeKey.valueOf("recv:"+sendableMsg.getMessageid());
		if(!this.channel.hasAttr(attributeKey)){
			 if(sendableMsg.getDupTimes()>maxresendtime){
				 
				 SendMsg unsceesssMsg = new SendMsg(sendableMsg
							.getRecvclientid(), sendableMsg
							.getMessageid(),
							messagePushService.MSG_SENDUNSUCCESS,
							sendableMsg.getSendclientid());
				 	messagePushService.getUnsucQue().offer(unsceesssMsg);
					
			 }
			 else{
				 sendableMsg.setDupTimes(sendableMsg.getDupTimes()+1);
				 messagePushService.sendMsg2Client(sendableMsg);
				 
				 logger.debug("第"+sendableMsg.getDupTimes()+"次"+sendableMsg.getSendclientid()+"发送给"+sendableMsg.getRecvclientid());
			 }
			 
		}else{
			

			channel.attr(attributeKey).remove();
			
			AttributeKey<String> attributeRecv=AttributeKey.valueOf(
					sendableMsg.getMessageid()+":recv");
			AttributeKey<String> attributeSend=AttributeKey.valueOf(
					sendableMsg.getMessageid()+":send");
			
			SendMsg sendMsg=new SendMsg();
			if(channel.hasAttr(attributeSend)){
				sendMsg.setSendclientid(channel.attr(attributeSend).getAndRemove());
			}
			
			if(channel.hasAttr(attributeRecv)){
				sendMsg.setClientid(channel.attr(attributeRecv).getAndRemove());
			}
			
			sendMsg.setSendmsgid(sendableMsg.getMessageid());
			sendMsg.setSendstate(messagePushService.MSG_SENDSUCCESS);
			messagePushService.offerSuccSend(sendMsg);
		}
	}

}
